<?php

// +----------------------------------------------------------------------
// | 图片模型
// +----------------------------------------------------------------------

class image_model extends model {

	protected $filterIds; //需要排重的图片id
	protected $url;
	
	public function _initialize() {
		$this->url = C('url');
	}

	//初始化
	public function init() {
		$this->filterIds = array();
	}

	//获取指定条件图片列表
	public function getList($map=array(), $limit='', $field='', $order='', $group='', $filter=false) {
		$field = $field ? $field : '*';
		$order = $order ? $order : 'id desc';
		$limit = $limit ? $limit : 20;
		if(!isset($map['status'])){
			$map['status'] = 1;
		}
		if (!isset($map['id']) && $filter && $this->filterIds) {
			$map['id'] = array('not in', implode(',', $this->filterIds));
		}
		$lists = $this->field($field)->where($map)->order($order)->limit($limit)->group($group)->findAll();
		return $lists;
	}

	//获取图片详细信息
	public function getInfo($id, $field='',$filter=false){
		$field = $field ? $field : '*';
		$map = array();
		if(is_numeric($id)){
			$map['id'] = $id;
		}else{
			$map = $id;
		}
		$lists = $this->field($field)->where($map)->limit(1)->findAll();
		if($lists){
			$lists = $this->format($lists,$filter);
			$lists = array_shift($lists);
		}
		return $lists;
	}

	//得到首页顶部头条
	public function getIndexTopList($catid, $filter=false) {
		$map = array();
		$map['status'] = 1;
		if ($catid)
			$map['catid1'] = $catid;
		$rows = $this->getList($map, 9, 'id,name,catid1,catid2,img,view,download,addtime,updatetime', 'rand()', '', $filter);
		return $rows;
	}

	

	//格式化获取的图片数据
	public function format($lists, $filter=false) {
		if(empty($lists)) return array();

		$Mcat = M('category');
		foreach ($lists as $k => $v) {
			$v['view_url'] = url('view',$v);
			$v['download_url'] = url('download',$v);
			$v['cat1_url'] = url('category',$v['catid1']);
			$v['cat2_url'] = url('category',$v['catid2']);
			$v['cat1_name'] = $Mcat->id2name($v['catid1']);
			$v['cat2_name'] = $Mcat->id2name($v['catid2']);
			$v['img'] = $v['img_160_120'] = imgurl($v['id'],'160_120');
			$v['img_480_360'] = imgurl($v['id'],'480_360');
			
			//时间处理
			if (isset($v['addtime']) && $v['addtime']) {
				$v['addtime_format'] = date('Y-m-d H:i',$v['addtime']);
			}
			if (isset($v['updatetime']) && $v['updatetime']) {
				$v['updatetime_format'] = date('Y-m-d H:i',$v['updatetime']);
			}
			if ($filter) {
				$this->filterIds[] = $v['id']; //加入排重列表
			}
			$lists[$k] = $v;
		}
		if ($filter) {
			$this->filterIds = array_flip(array_flip($this->filterIds));
		}
		return $lists;
	}

	//加入软件过滤列表
	public function addFilterIds($lists) {
		if (empty($lists) || !is_array($lists))
			return array();
		$ids = array();
		foreach ($lists as $k => $v) {
			$this->filterIds[] = $ids[] = $v['id'];
		}
		$this->filterIds = array_flip(array_flip($this->filterIds));
		return $ids;
	}

}